<?php

defined('EN_CODE') or die(__FILE__.': Direct Access Denied');

use Code\Model;

function listado_total_marcas() {
    $model = Model::getInstance();
    $query = "SELECT * FROM marcas ORDER BY nombre";
    $result = $model->query($query);
    if (!$result || $model->numRows($result)==0) {
        return null;
    }
    return $model->fetchAll($result);
}

function una_marca($id_marca) {
    $model = Model::getInstance();
    $id_marca_escaped = preg_replace('/[^\d]/', '', $id_marca);
    $query = "SELECT * FROM marcas WHERE id_marca=$id_marca_escaped";
    $result = $model->query($query);
    return $model->fetchOne($result);
}

function una_marca_con(array $parameters) {
    $model = Model::getInstance();
    $i = 0;
    $conditions = "";
    foreach ($parameters as $field => $value) {
        if ($i!=0) {
            $conditions .= " OR ";
        } else {
            $i++;
        }
        $conditions .= " $field='$value' ";
    }
    $query = "SELECT * FROM marcas WHERE ($conditions)";
    $result = $model->query($query);
    return $model->fetchOne($result);
}

function upsert_marca(array $parameters, $id_marca=null) {
    $model = Model::getInstance();
    if (is_null($id_marca)) {
        return crear_marca($parameters);
    } else {
        return editar_marca($parameters, $id_marca);
    }
}

function crear_marca(array $parameters) {
    $model = Model::getInstance();
    $campos = "INSERT INTO marcas (";
    $valores = " VALUES(";
    $cantidad_campos = count($parameters);
    $cantidad_campos_procesados = 0;
    foreach ($parameters as $campo => $valor) {
        $campos .= $campo;
        if (++$cantidad_campos_procesados!=$cantidad_campos) {
            $campos .= ', ';
        } else {
            $campos .= ')';
        }
        $valores .= "'$valor'";
        if ($cantidad_campos_procesados!=$cantidad_campos) {
            $valores .= ', ';
        } else {
            $valores .= ')';
        }
    }
    $query = $campos.$valores;
    return $model->query($query);
}

function editar_marca(array $parameters, $id_marca) {
    $model = Model::getInstance();
    if (!empty($parameters)) {
        $query = "UPDATE marcas SET ";
        $i = 0;
        foreach ($parameters as $field => $value) {
            $query .= " $field='$value'";
            if (++$i < count($parameters)) {
                $query .= ", ";
            }
        }
        $query .= " WHERE id_marca=$id_marca";
        if ($model->query($query)) {
            return $id_marca;
        }
        return false;
    }
    return false;
}

function eliminar_marca($id_marca) {
    $model = Model::getInstance();
    $id_marca_escaped = preg_replace('/[^\d]/', '', $id_marca);
    $query = "DELETE FROM marcas WHERE id_marca=$id_marca_escaped";
    return $model->query($query);
}

?>
